/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package su.samlib.informer.database.controllers;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import su.samlib.informer.database.model.Library;
import su.samlib.informer.database.model.UserAuthors;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import su.samlib.informer.database.controllers.exceptions.IllegalOrphanException;
import su.samlib.informer.database.controllers.exceptions.NonexistentEntityException;
import su.samlib.informer.database.model.Author;
import su.samlib.informer.database.model.Book;

/**
 *
 * @author rikland
 */
public class AuthorJpaController implements Serializable {

    public AuthorJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Author author) {
        if (author.getUserAuthorsList() == null) {
            author.setUserAuthorsList(new ArrayList<UserAuthors>());
        }
        if (author.getBookList() == null) {
            author.setBookList(new ArrayList<Book>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Library libraryId = author.getLibraryId();
            if (libraryId != null) {
                libraryId = em.getReference(libraryId.getClass(), libraryId.getLibraryId());
                author.setLibraryId(libraryId);
            }
            List<UserAuthors> attachedUserAuthorsList = new ArrayList<UserAuthors>();
            for (UserAuthors userAuthorsListUserAuthorsToAttach : author.getUserAuthorsList()) {
                userAuthorsListUserAuthorsToAttach = em.getReference(userAuthorsListUserAuthorsToAttach.getClass(), userAuthorsListUserAuthorsToAttach.getUserAuthorsPK());
                attachedUserAuthorsList.add(userAuthorsListUserAuthorsToAttach);
            }
            author.setUserAuthorsList(attachedUserAuthorsList);
            List<Book> attachedBookList = new ArrayList<Book>();
            for (Book bookListBookToAttach : author.getBookList()) {
                bookListBookToAttach = em.getReference(bookListBookToAttach.getClass(), bookListBookToAttach.getBookId());
                attachedBookList.add(bookListBookToAttach);
            }
            author.setBookList(attachedBookList);
            em.persist(author);
            if (libraryId != null) {
                libraryId.getAuthorList().add(author);
                libraryId = em.merge(libraryId);
            }
            for (UserAuthors userAuthorsListUserAuthors : author.getUserAuthorsList()) {
                Author oldAuthorOfUserAuthorsListUserAuthors = userAuthorsListUserAuthors.getAuthor();
                userAuthorsListUserAuthors.setAuthor(author);
                userAuthorsListUserAuthors = em.merge(userAuthorsListUserAuthors);
                if (oldAuthorOfUserAuthorsListUserAuthors != null) {
                    oldAuthorOfUserAuthorsListUserAuthors.getUserAuthorsList().remove(userAuthorsListUserAuthors);
                    oldAuthorOfUserAuthorsListUserAuthors = em.merge(oldAuthorOfUserAuthorsListUserAuthors);
                }
            }
            for (Book bookListBook : author.getBookList()) {
                Author oldAuthorIdOfBookListBook = bookListBook.getAuthorId();
                bookListBook.setAuthorId(author);
                bookListBook = em.merge(bookListBook);
                if (oldAuthorIdOfBookListBook != null) {
                    oldAuthorIdOfBookListBook.getBookList().remove(bookListBook);
                    oldAuthorIdOfBookListBook = em.merge(oldAuthorIdOfBookListBook);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Author author) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Author persistentAuthor = em.find(Author.class, author.getAuthorId());
            Library libraryIdOld = persistentAuthor.getLibraryId();
            Library libraryIdNew = author.getLibraryId();
            List<UserAuthors> userAuthorsListOld = persistentAuthor.getUserAuthorsList();
            List<UserAuthors> userAuthorsListNew = author.getUserAuthorsList();
            List<Book> bookListOld = persistentAuthor.getBookList();
            List<Book> bookListNew = author.getBookList();
            List<String> illegalOrphanMessages = null;
            for (UserAuthors userAuthorsListOldUserAuthors : userAuthorsListOld) {
                if (!userAuthorsListNew.contains(userAuthorsListOldUserAuthors)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain UserAuthors " + userAuthorsListOldUserAuthors + " since its author field is not nullable.");
                }
            }
            for (Book bookListOldBook : bookListOld) {
                if (!bookListNew.contains(bookListOldBook)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Book " + bookListOldBook + " since its authorId field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (libraryIdNew != null) {
                libraryIdNew = em.getReference(libraryIdNew.getClass(), libraryIdNew.getLibraryId());
                author.setLibraryId(libraryIdNew);
            }
            List<UserAuthors> attachedUserAuthorsListNew = new ArrayList<UserAuthors>();
            for (UserAuthors userAuthorsListNewUserAuthorsToAttach : userAuthorsListNew) {
                userAuthorsListNewUserAuthorsToAttach = em.getReference(userAuthorsListNewUserAuthorsToAttach.getClass(), userAuthorsListNewUserAuthorsToAttach.getUserAuthorsPK());
                attachedUserAuthorsListNew.add(userAuthorsListNewUserAuthorsToAttach);
            }
            userAuthorsListNew = attachedUserAuthorsListNew;
            author.setUserAuthorsList(userAuthorsListNew);
            List<Book> attachedBookListNew = new ArrayList<Book>();
            for (Book bookListNewBookToAttach : bookListNew) {
                bookListNewBookToAttach = em.getReference(bookListNewBookToAttach.getClass(), bookListNewBookToAttach.getBookId());
                attachedBookListNew.add(bookListNewBookToAttach);
            }
            bookListNew = attachedBookListNew;
            author.setBookList(bookListNew);
            author = em.merge(author);
            if (libraryIdOld != null && !libraryIdOld.equals(libraryIdNew)) {
                libraryIdOld.getAuthorList().remove(author);
                libraryIdOld = em.merge(libraryIdOld);
            }
            if (libraryIdNew != null && !libraryIdNew.equals(libraryIdOld)) {
                libraryIdNew.getAuthorList().add(author);
                libraryIdNew = em.merge(libraryIdNew);
            }
            for (UserAuthors userAuthorsListNewUserAuthors : userAuthorsListNew) {
                if (!userAuthorsListOld.contains(userAuthorsListNewUserAuthors)) {
                    Author oldAuthorOfUserAuthorsListNewUserAuthors = userAuthorsListNewUserAuthors.getAuthor();
                    userAuthorsListNewUserAuthors.setAuthor(author);
                    userAuthorsListNewUserAuthors = em.merge(userAuthorsListNewUserAuthors);
                    if (oldAuthorOfUserAuthorsListNewUserAuthors != null && !oldAuthorOfUserAuthorsListNewUserAuthors.equals(author)) {
                        oldAuthorOfUserAuthorsListNewUserAuthors.getUserAuthorsList().remove(userAuthorsListNewUserAuthors);
                        oldAuthorOfUserAuthorsListNewUserAuthors = em.merge(oldAuthorOfUserAuthorsListNewUserAuthors);
                    }
                }
            }
            for (Book bookListNewBook : bookListNew) {
                if (!bookListOld.contains(bookListNewBook)) {
                    Author oldAuthorIdOfBookListNewBook = bookListNewBook.getAuthorId();
                    bookListNewBook.setAuthorId(author);
                    bookListNewBook = em.merge(bookListNewBook);
                    if (oldAuthorIdOfBookListNewBook != null && !oldAuthorIdOfBookListNewBook.equals(author)) {
                        oldAuthorIdOfBookListNewBook.getBookList().remove(bookListNewBook);
                        oldAuthorIdOfBookListNewBook = em.merge(oldAuthorIdOfBookListNewBook);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = author.getAuthorId();
                if (findAuthor(id) == null) {
                    throw new NonexistentEntityException("The author with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Author author;
            try {
                author = em.getReference(Author.class, id);
                author.getAuthorId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The author with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<UserAuthors> userAuthorsListOrphanCheck = author.getUserAuthorsList();
            for (UserAuthors userAuthorsListOrphanCheckUserAuthors : userAuthorsListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Author (" + author + ") cannot be destroyed since the UserAuthors " + userAuthorsListOrphanCheckUserAuthors + " in its userAuthorsList field has a non-nullable author field.");
            }
            List<Book> bookListOrphanCheck = author.getBookList();
            for (Book bookListOrphanCheckBook : bookListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Author (" + author + ") cannot be destroyed since the Book " + bookListOrphanCheckBook + " in its bookList field has a non-nullable authorId field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Library libraryId = author.getLibraryId();
            if (libraryId != null) {
                libraryId.getAuthorList().remove(author);
                libraryId = em.merge(libraryId);
            }
            em.remove(author);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Author> findAuthorEntities() {
        return findAuthorEntities(true, -1, -1);
    }

    public List<Author> findAuthorEntities(int maxResults, int firstResult) {
        return findAuthorEntities(false, maxResults, firstResult);
    }

    private List<Author> findAuthorEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Author.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Author findAuthor(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Author.class, id);
        } finally {
            em.close();
        }
    }

    public int getAuthorCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Author> rt = cq.from(Author.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
